11. Stack vs Heap
Stack vs Heap
ND079 C1 L1 A08 Stack Vs Heap
Java uses two different memory regions when running an application: The stack and the heap.
- The stack is used to store primitives and object references, while the heap is used to store the objects themselves.
- Items in the stack get added and removed as a given method executes, while objects in the heap stay until the application is done (or at least, until there are no object references using them from anywhere in the program, at which point they are removed by the garbage collector).
- Items are removed from the stack in a **Last-In-First-Out (LIFO) **order, meaning that the last element you added to the stack is the first that gets popped off the stack.
- Remember that the items in a stack are only maintained as long as the related method is running. By the time a given method has finished running, all of the items on the stack for that method will have been removed.
- Objects in the heap are accessible from anywhere in the program, while items on a given stack can only be accessed by the related method.
QUIZ QUESTION::
Each of the statements below either describes a stack or a heap. Can you identify which is which?
ANSWER CHOICES:
Statement |
Stack or heap? |
---|---|
Stores primitive types and object references. |
|
Stores Objects. |
|
Removes data in a LIFO manner when data is no longer needed. |
|
Global memory where data can be accessed from anywhere in the program. |
SOLUTION:
Statement |
Stack or heap? |
---|---|
Stores primitive types and object references. |
|
Removes data in a LIFO manner when data is no longer needed. |
|
Stores Objects. |
|
Global memory where data can be accessed from anywhere in the program. |
|
Stores Objects. |
|
Global memory where data can be accessed from anywhere in the program. |
|
Stores primitive types and object references. |
|
Removes data in a LIFO manner when data is no longer needed. |